package com.TheyChat.service.config.core.exception;

import com.TheyChat.service.config.core.entity.ResponseMessage;
import com.TheyChat.service.config.core.entity.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Configuration
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    //声明要捕获的异常
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseMessage defaultExceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception e) {
        e.printStackTrace();
        //业务异常：
        if (e instanceof BusinessException) {
            BusinessException businessException = (BusinessException) e;
            return Result.error(ResponseMessageErrorCodeEnum.BUSINESS_EXCEPTION.getCode(), businessException.getMessage());
        }
        //未认证异常：
        else if (e instanceof NotAuthenticatedException) {
            NotAuthenticatedException notAuthenticatedException = (NotAuthenticatedException) e;
            return Result.error(ResponseMessageErrorCodeEnum.NOT_AUTHENTICATED.getCode(), notAuthenticatedException.getMessage());
        }
        //未授权异常：
        else if (e instanceof NotAuthorizedException) {
            NotAuthorizedException notAuthorizedException = (NotAuthorizedException) e;
            return Result.error(ResponseMessageErrorCodeEnum.NOT_AUTHORIZED.getCode(), notAuthorizedException.getMessage());
        }
        // 参数不合法异常
        else if (e instanceof IllegalArgumentException) {
            return Result.error(ResponseMessageErrorCodeEnum.BUSINESS_EXCEPTION.getCode(), e.getMessage());
        }
        // 参数校验异常
        else if (e instanceof MethodArgumentNotValidException) {
            return Result.error(ResponseMessageErrorCodeEnum.BUSINESS_EXCEPTION.getCode(), ((MethodArgumentNotValidException) e).getBindingResult().getAllErrors().get(0).getDefaultMessage());
        }
        //未知错误
        else {

            StringBuilder sb = new StringBuilder();
            sb.append("\r\n-------------------------------------------------------------------\r\n");
            sb.append(String.format("[ServerName:%s]\r\n", request.getServerName()));
            sb.append(String.format("[ServerPort:%d]\r\n", request.getServerPort()));
            sb.append(String.format("[RemoteAddr:%s]\r\n", request.getRemoteAddr()));
            sb.append(String.format("[RemotePort:%d]\r\n", request.getRemotePort()));
            sb.append(String.format("[RequestURI:%s]\r\n", request.getRequestURI()));
            sb.append(String.format("[Method:%s]\r\n", request.getMethod()));
            sb.append(String.format("[ErrorMsg:%s]\r\n", e.getMessage()));
            sb.append(String.format("[StackTrace:%s]\r\n", getStackTraceMsg(e)));
            sb.append("-------------------------------------------------------------------\r\n");
            log.error(sb.toString());
            return Result.error(ResponseMessageErrorCodeEnum.ERROR.getCode(), e.getMessage() + getStackTraceMsg(e));
        }
    }


    private String getStackTraceMsg(Exception e) {

        StringBuffer sb = new StringBuffer();
        StackTraceElement[] stackArray = e.getStackTrace();
        for (int i = 0; i < stackArray.length; i++) {
            StackTraceElement element = stackArray[i];
            sb.append(element.toString() + "\n");
        }
        return sb.toString();
    }


}
